package nc.ui.uif2.actions;

import java.awt.event.ActionEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import nc.bs.uif2.BusinessExceptionAdapter;
import nc.bs.uif2.validation.IValidationService;
import nc.bs.uif2.validation.ValidationException;
import nc.ui.querytemplate.querytree.IIconDecorator;
import nc.ui.uif2.NCAction;
import nc.ui.uif2.UIState;
import nc.ui.uif2.editor.IEditor;
import nc.ui.uif2.model.AbstractAppModel;

public class SaveAction extends NCAction
{
  private static final long serialVersionUID = 1L;
  public static final Icon SAVE_ICON = new ImageIcon(IIconDecorator.class.getResource("/images/qrytemplate/save.png"));
  private AbstractAppModel model;
  private IEditor editor;
  IValidationService validationService;

  public SaveAction()
  {
    ActionInitializer.initializeAction(this, 0);
    putValue("SmallIcon", SAVE_ICON);
  }

  public void doAction(ActionEvent e)
    throws Exception
  {
    Object value = this.editor.getValue();

    validate(value);

    if (this.model.getUiState() == UIState.ADD) {
      this.model.add(value);
    }
    if (this.model.getUiState() == UIState.EDIT) {
      this.model.update(value);
    }
    this.model.setUiState(UIState.NOT_EDIT);
  }

  protected void validate(Object value)
  {
    if (this.validationService == null)
      return;
    try {
      this.validationService.validate(value);
    } catch (ValidationException e) {
      throw new BusinessExceptionAdapter(e);
    }
  }

  protected boolean isActionEnable()
  {
    return (this.model.getUiState() == UIState.EDIT) || (this.model.getUiState() == UIState.ADD);
  }

  public void setModel(AbstractAppModel model) {
    this.model = model;
    model.addAppEventListener(this);
  }

  public void setEditor(IEditor editor) {
    this.editor = editor;
  }

  public IValidationService getValidationService() {
    return this.validationService;
  }

  public void setValidationService(IValidationService validationService) {
    this.validationService = validationService;
  }

  public AbstractAppModel getModel() {
    return this.model;
  }

  public IEditor getEditor() {
    return this.editor;
  }
}